var g_canvas;
var g_context;
var g_colorContainer;
var socket = io.connect('http://localhost');
var g_userId = null;

window.onload = function()
{
    g_canvas = document.getElementById( "canvas" );
    g_context = g_canvas.getContext( "2d" );
    g_colorContainer = document.getElementById( "color" );
}

socket.on('news', function ( gameData ) 
{
    g_userId = gameData.id;
    var users = gameData.allUsers;
    refreshColor(users[g_userId].color);
    rewrite( users );    
});

socket.on( 'redraw', function( gameData )
{
    rewrite( gameData.allUsers );                
});

socket.on( 'colorContainer', function(color)
{
    refreshColor(color);    
});

function refreshColor(color)
{
    g_colorContainer.style.background = color;
}

window.addEventListener('keydown', onKeyDownEvent, false);
window.addEventListener('keyup', onKeyUpEvent, false);

function onKeyDownEvent(event) 
{  
    socket.emit('keyDownEvent',  {'keyCode': event.keyCode, 'id': g_userId});
}

function onKeyUpEvent(event) 
{  
    socket.emit('keyUpEvent',  {'keyCode': event.keyCode, 'id': g_userId});
}

function rewrite( users )
{
    g_context.clearRect( 0, 0, g_canvas.width, g_canvas.height );
    for( i = 0; i < users.length; i++ )
    {
        drawUserFrame( g_context, users[i] );
    }
}
